package cn.fintecher.pangolin.service.manage.service;

import cn.fintecher.pangolin.common.enums.BaseSelect;
import cn.fintecher.pangolin.common.exception.BadRequestException;
import cn.fintecher.pangolin.common.model.DepartmentModel;
import cn.fintecher.pangolin.common.model.UserModel;
import cn.fintecher.pangolin.common.response.LoginResponse;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * @Auther: xiaqun
 * @Description:
 * @Date: 10:55 2019/8/14
 */

@Service("baseService")
public class BaseService {
    @Autowired
    private RedisTemplate<String, Object> jsonRedisTemplate;

    /**
     * 获取用户信息
     */
    public UserModel getUserByToken(String token) {
        LoginResponse response = (LoginResponse) jsonRedisTemplate.opsForValue().get(token);
        if (Objects.isNull(response)) {
            throw new BadRequestException(null, "user", "token.is.error");
        }
        return response.getUserModel();
    }

    /**
     * 获取用户部门信息
     */
    DepartmentModel getDepartmentByToken(String token) {
        LoginResponse response = (LoginResponse) jsonRedisTemplate.opsForValue().get(token);
        if (Objects.isNull(response)) {
            throw new BadRequestException(null, "user", "token.is.error");
        }
        return response.getDepartmentModel();
    }

    public LoginResponse getUserSessionByToken(String token) {
        LoginResponse response = (LoginResponse) jsonRedisTemplate.opsForValue().get(token);
        if (Objects.isNull(response)) {
            throw new BadRequestException(null, "user", "token.is.error");
        }
        return response;
    }

    /**
     * 获取登录IP
     */
    public String getAddressIP(HttpServletRequest request) {
        if (Objects.isNull(request)) {
            return null;
        }
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    /**
     * 拼接es合规过滤条件
     */
    public void spliceBuilder(BoolQueryBuilder builder, UserModel userModel) {
        if (userModel.getIsCheck().equals(BaseSelect.YES)) {
            builder.must(QueryBuilders.termsQuery("principalId.keyword", userModel.getPrincipalIds()));
        }
    }
}
